<template>
  <Table ref="tableRef" :columns="columns" :data="loadData" :alert="false" bordered>
    <template #operator>
      <div class="table-search">
        <div>
          <span class="table-search-box">
            名称：
            <a-input v-model:value="searchValue" placeholder="请输入集群名称" style="width: 240px" allowClear>
              <template #prefix>
                <SvgIcon class="iconDef" :name="'search'" :color="'#d9d9d9'" width="16" height="16" />
              </template>
            </a-input>
          </span>

          <span class="table-search-box">
            搭建日期：
            <a-range-picker v-model:value="selectValue" :valueFormat="'YYYY-MM-DD'" />
          </span>
        </div>
        <div class="table-search-btn">
          <a-button class="actionBtn" type="primary" ghost @click="tableRef.refresh(true)">
            <SvgIcon class="iconDef" :name="'search'" :color="'#2590FF'" width="16" height="16" />
            查询
          </a-button>

          <a-button class="actionBtn" type="primary" ghost @click="refreshTable">
            <SvgIcon class="iconDef" :name="'refresh'" :color="'#2590FF'" width="16" height="16" />
            重置
          </a-button>
        </div>
      </div>
      <div style="margin-top: 16px">
        <a-button type="primary" @click="addCluster">
          <PlusOutlined />
          连接已有集群
        </a-button>
      </div>
    </template>
    <template #bodyCell="{ column, record, index }">
      <template v-if="column.dataIndex === 'index'"> {{ index + 1 }} </template>
      <template v-if="column.dataIndex === 'action'">
        <div class="table-operation">
          <a @click="handelDetial(record)">详情</a>
          <a @click="editCluster(record)">编辑</a>
          <a @click="deleteCluster(record)">删除</a>
        </div>
      </template>
    </template>
  </Table>

  <BasicModal
    ref="addAllocation"
    :title="`${modelType}集群`"
    width="1000px"
    @emit-callback-fn="addCallbackFn($event)"
    :confirmLoading="editClusterManagementLoading"
  >
    <template #content>
      <SchemaForm ref="formRef" />
      <div class="code-mirror-editor">
        <div class="code-mirror-editor-upload">
          <div class="code-mirror-form">
            <span>*</span>
            <span>kubeConfig：</span>
          </div>
          <div class="code-mirror-editor-edit">
            <CodeMirrorEditor
              ref="yamlRef"
              v-model:value="code"
              mode="yaml"
              style="height: 500px"
              :lint="true"
              :readonly="readonly"
            />
          </div>
          <div class="code-mirror-msg" v-if="codeFlag">请输入kubeConfig</div>
        </div>
      </div>
    </template>
  </BasicModal>
</template>

<script setup lang="ts">
import { PlusOutlined, ExclamationCircleOutlined } from '@ant-design/icons-vue';
import {
  queryClusterPageListFun,
  addClusterDataFun,
  deleteClusterDataFun,
  putClusterDataFun,
  getExistsSpaceLimit,
} from '@/api/operationManagement';
import { useForm } from '@/components/SchemaForm/index';
import type { FormSchema } from '@/components/SchemaForm';
import { message } from 'ant-design-vue';
import { Modal } from 'ant-design-vue';
import { createVNode } from 'vue';
const searchValue = ref('');
const selectValue = ref<any>();
const columns = [
  { dataIndex: 'index', title: '序号', align: 'center', width: 100 },
  { dataIndex: 'name', title: '名称', align: 'center', ellipsis: true },
  { dataIndex: 'alias', title: '别名', align: 'center', ellipsis: true },
  { dataIndex: 'description', title: '描述', align: 'center', width: 300, ellipsis: true },
  { dataIndex: 'creator', title: '搭建人', align: 'center', ellipsis: true },
  { dataIndex: 'createTime', title: '搭建时间', align: 'center', ellipsis: true },
  {
    title: '操作',
    dataIndex: 'action',
    align: 'center',
    fixed: 'right',
    width: 160,
  },
];

const tableRef = ref<any>('');

const loadData = async (parameter: any) => {
  const parameObj = {
    currentPage: parameter.current,
    pageSize: parameter.size,
    condition: {
      condition: searchValue.value,
      startDate: selectValue.value && selectValue.value[0],
      endDate: selectValue.value && selectValue.value[1],
    },
  };
  const data = await getList(parameObj);
  return data;
};

const codeFlag = ref<boolean>(false);
const readonly = ref<boolean>(false);

//获取表格数据
const getList = async (parameObj: OperationManagement.tableParamsList) => {
  return await queryClusterPageListFun(parameObj).then((res) => {
    const data = {
      total: res.totalCount,
      current: res.currentPage,
      pageSize: res.pageSize,
      records: res.records,
    };
    return data;
  });
};

//刷新表格数据
const refreshTable = () => {
  searchValue.value = '';
  readonly.value = false;
  selectValue.value = undefined;
  tableRef.value.refresh(true);
};

const addAllocation: any = ref(null);

//表格详情
const handelDetial = (record: any) => {
  nextTick(() => {
    formRef.setFieldsValue(record);
    code.value = record.kubeConfig;
    readonly.value = true;
    formRef.setSchemaFormProps({ disabled: true });
  });
  addAllocation.value.showModal(record, '关闭');
};

const [SchemaForm, formRef] = useForm({
  schemas: [
    {
      field: 'name',
      label: '名称',
      labelWidth: 90,
      required: true,
      colProps: {
        span: 12,
      },
      rules: [
        {
          required: true,
          validator: (_, value: any) => {
            return new Promise((resolve, reject) => {
              if (!value) {
                reject(new Error('名称不能为空'));
              } else if (value.length > 20) {
                reject(new Error('请输入20字符以内的名称'));
              } else {
                resolve();
              }
            });
          },
        },
      ],
      component: 'Input',
    },
    {
      field: 'alias',
      label: '别名',
      required: false,
      labelWidth: 90,
      colProps: {
        span: 12,
      },
      component: 'Input',
    },
    {
      field: 'description',
      label: '描述',
      labelWidth: 90,
      required: false,
      colProps: {
        span: 24,
      },
      component: 'InputTextArea',
    },
  ] as FormSchema[],
});

enum ClusterType {
  add = '连接已有',
  edit = '编辑',
}

const yamlRef = ref(null);
const code = ref<string>('');
const modelType = ref<string>(ClusterType.add);

//添加集群
const addCluster = () => {
  modelType.value = ClusterType.add;
  code.value = '';
  readonly.value = false;
  addAllocation.value.showModal();
};

//编辑集群
const editCluster = (record: any) => {
  modelType.value = ClusterType.edit;
  code.value = record.kubeConfig;
  console.log(code.value);
  addAllocation.value.showModal(record);
  readonly.value = false;
  nextTick(() => {
    formRef.setFieldsValue(record);
  });
};

//删除集群
const deleteCluster = async (record: any) => {
  await getExistsSpaceLimit(record.uuid).then((res: any) => {
    // data返回true代表有限制，false调用删除接口
    if (!res) {
      deleteClusterData(record);
    } else {
      Modal.confirm({
        title: '您还不能删除该集群！',
        icon: createVNode(ExclamationCircleOutlined),
        content: '该集群已绑定环境，请解绑后再尝试删除！',
        centered: true,
        okText: '确定',
        cancelText: '取消',
      });
    }
  });
};

const deleteClusterData = async (record: any) => {
  Modal.confirm({
    title: '提示',
    icon: '',
    centered: true,
    content: createVNode('div', { style: 'color:black;' }, `确定要删除“集群：${record.name}”这一项数据吗？`),
    async onOk() {
      await deleteClusterDataFun(record.uuid).then(() => {
        message.success('删除成功');
        tableRef.value.refresh(true);
      });
    },
    onCancel() {},
  });
};
const editClusterManagementLoading = ref<boolean>(false);
const addCallbackFn = async (obj: any) => {
  const data = await formRef.validate();
  let parameObj: any = {
    ...data,
    kubeConfig: code.value,
  };

  if (code.value === '') {
    codeFlag.value = true;
    return;
  }
  codeFlag.value = false;
  editClusterManagementLoading.value = true;
  if (modelType.value === ClusterType.add) {
    await addClusterDataFun(parameObj)
      .then(() => {
        message.success('添加成功');
        tableRef.value.refresh(true);
        addAllocation.value.hideModal();
      })
      .finally(() => {
        editClusterManagementLoading.value = false;
      });
  }

  if (modelType.value === ClusterType.edit) {
    parameObj = {
      ...parameObj,
      uuid: obj.propsData.uuid,
    };
    await putClusterDataFun(parameObj)
      .then(() => {
        message.success('编辑成功');
        tableRef.value.refresh(true);
        addAllocation.value.hideModal();
      })
      .finally(() => {
        editClusterManagementLoading.value = false;
      });
  }
};
</script>

<style scoped lang="less">
.code-mirror-editor {
  // display: flex;
  // flex-direction: column;
  width: 100%;
  &-upload {
    display: flex;
    justify-content: flex-start;
    align-items: flex-start;
    padding-bottom: 16px;
    position: relative;
    color: #2590ff;
    span:nth-child(1) {
      color: #fd5a43;
    }
    span:nth-child(2) {
      color: black;
      display: inline-block;
      width: 90px;
    }
    span:nth-child(3) {
      cursor: pointer;
    }
  }
  .code-mirror-form {
    width: 90px;
    display: flex;
  }
  &-edit {
    margin-bottom: 24px;
    width: calc(100% - 90px);
  }
}
.table-search {
  border-bottom: 1px solid #e7eff8;
  padding-bottom: 16px;
}

.code-mirror-msg {
  color: #fd5a43;
  margin-left: 90px;
  position: absolute;
  bottom: 8px;
}
</style>
